package com.be.beadmin.design.controller;

import com.alibaba.excel.EasyExcel;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.utils.ResultModel;
import com.be.beadmin.design.dto.input.ProductBomDto;
import com.be.beadmin.design.dto.output.ProductBomEx;
import com.be.beadmin.design.service.ProductBomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
* @author zmy
* @date 2023-03-22
**/
@RestController
public class ProductBomController {

    @Autowired
    private  ProductBomService productBomService;


    @PostMapping(value = "/design/getProductBomByPage")
    public ResultModel getProductBomByPage(@RequestBody PageEntity pageEntity)  {
        return ResultModel.success(productBomService.getProductBomByPage(pageEntity)) ;
    }

    @PostMapping("/design/addProductBom")
    public ResultModel addProductBom(@RequestBody ProductBomDto productBomDto){
        productBomService.addProductBom(productBomDto);
        return ResultModel.success(ResultModel.ADD);
    }

    @PostMapping("/design/delProductBom")
    public ResultModel delProductBom(@RequestBody ProductBomDto productBomDto){
        productBomService.delProductBom(productBomDto.getId());
        return ResultModel.success(ResultModel.DELETE);
    }


    @PostMapping("/design/updateProductBom")
    public ResultModel updateProductBom(@RequestBody ProductBomDto productBomDto){
        productBomService.updateProductBom(productBomDto);
        return ResultModel.success(ResultModel.UPDATE);
    }


    @PostMapping("/design/exportProductBom")
    public void exportProductBom(HttpServletResponse response ,@RequestBody PageEntity pageEntity) throws IOException {
        Page<ProductBomEx> productBomPage = productBomService.getProductBomByPage(pageEntity);
        List<ProductBomEx> productBomExes = productBomPage.getContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("ProductBom接口", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ProductBomEx.class).sheet("sheet1").doWrite(productBomExes);
    }


}